// Package service
// @File: user_service.go
// @Description:
// @Author: YaoRuiQi
// @Date: 2025/8/23 03:01

package service

import (
	"GinStandardTemplate/internal/dto"
	"GinStandardTemplate/internal/pkg/bizerror"
	"GinStandardTemplate/internal/pkg/codes"
	"GinStandardTemplate/internal/pkg/contextUtils"
	"GinStandardTemplate/internal/pkg/jwt"
	"GinStandardTemplate/utils/i18n"
	"GinStandardTemplate/utils/redisUtils"
	"context"
	"fmt"
	"time"
)

type UserService struct{}

func NewUserService() *UserService {
	return &UserService{}
}

func (s *UserService) Login(ctx *contextUtils.RequestContext, username, password string) (*dto.UserLoginResponse, *bizerror.BizError) {
	// TODO: 模拟登录
	if username != "user01" {
		return nil, bizerror.NewBizError(
			codes.AccountNotExist,
			i18n.GetMessage(ctx, codes.AccountNotExist.MessageID(), nil),
		)
	}
	if password != "123456" {
		return nil, bizerror.NewBizError(
			codes.PasswordError,
			i18n.GetMessage(ctx, codes.PasswordError.MessageID(), nil),
		)
	}
	token, expireAt, err := jwt.JWTManager.GenerateJWT(1, "admin", 0, 24*7)
	if err != nil {
		return nil, bizerror.NewBizError(
			codes.InternalError,
			i18n.GetMessage(ctx, codes.InternalError.MessageID(), nil),
		)
	}

	// 展示写入Redis缓存
	redisCtx, cancel := context.WithTimeout(ctx.Ctx, time.Second*5)
	defer cancel()
	if err := redisUtils.RedisClient.Set(redisCtx, fmt.Sprintf("user:%d", 1), token, time.Second*60); err != nil {
		return nil, bizerror.NewBizError(
			codes.InternalError,
			i18n.GetMessage(ctx, codes.InternalError.MessageID(), nil),
		)
	}

	return &dto.UserLoginResponse{
		Token:    token,
		ExpireAt: expireAt,
	}, nil
}

func (s *UserService) Me(ctx *contextUtils.RequestContext) (*dto.UserInfoItem, *bizerror.BizError) {
	return &dto.UserInfoItem{
		UserID:   ctx.UserData.UserID,
		Username: "user01",
	}, nil
}
